package com.sjgs.gis.utils;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.springframework.cloud.netflix.eureka.EurekaDiscoveryClient;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

public class GrpcChannelUtils {
    private final static int MAX_MSG_SIZE = 5 * 1024 * 1024;

    /**
     * @param instanceId
     * @return
     */
    public static ManagedChannel getChannelByInstanceId(EurekaDiscoveryClient discoveryClient, String serviceId, String instanceId) {
        Optional<String> opt_target = discoveryClient.getInstances(serviceId)
                .stream()
                .filter(it -> it.getInstanceId().equals(instanceId))
                .map(it -> {
                    return it.getHost() + ":" + (it.getPort() + 1);
                }).findAny();
        if (opt_target.isPresent()) {
            System.out.println(opt_target.get());
            return getChannel(opt_target.get());
        } else {
            return null;
        }
    }

    public static ManagedChannel getChannel(String target) {
        return ManagedChannelBuilder
                .forTarget(target)
                .usePlaintext()
                .enableRetry()
                .maxRetryAttempts(5)
                .keepAliveTime(5, TimeUnit.MINUTES)
                .keepAliveWithoutCalls(true)
                .keepAliveTimeout(10, TimeUnit.MINUTES)
                .perRpcBufferLimit(MAX_MSG_SIZE)
                .build();
    }
}
